package com.sky.service.impl;

import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.sl.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.fasterxml.jackson.databind.type.LogicalType.Map;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end,LocalTime.MAX);

        List<LocalDate> dateList = new ArrayList<>();
        List<Double> amountList = new ArrayList<>();
        Double AmountSummary = 0.0;

        dateList.add(begin);
        while (end.isAfter(begin)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        turnoverReportVO.setDateList(StringUtils.join(dateList,","));

        List<Orders> orderList = orderMapper.GetOrderByDuring(beginTime,endTime, Orders.COMPLETED);

            for (LocalDate localDate : dateList) {
                if(orderList != null && orderList.size() > 0) {
                    LocalDateTime beginT = LocalDateTime.of(localDate, LocalTime.MIN);
                    LocalDateTime endT = LocalDateTime.of(localDate, LocalTime.MAX);
                    for (Orders order : orderList) {
                        if (beginT.isBefore(order.getCheckoutTime()) && endT.isAfter(order.getCheckoutTime())) {
                            if (order.getAmount() != null) {
                                AmountSummary += order.getAmount().doubleValue();
                            } else AmountSummary += 0.0;
                        }
                    }
                }
                amountList.add(AmountSummary);
                AmountSummary = 0.0;
            }

        turnoverReportVO.setTurnoverList(StringUtils.join(amountList,","));

        return turnoverReportVO;
    }

    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end,LocalTime.MAX);

        List<LocalDate> dateList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        int newUser = 0;
        int totalUser = userMapper.getTotalUserByCreateTime(beginTime);

        dateList.add(begin);
        while (end.isAfter(begin)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        UserReportVO userReportVO = new UserReportVO();
        userReportVO.setDateList(StringUtils.join(dateList,","));

        List<User> userList = userMapper.getUserByCreateTime(beginTime,endTime);

        for (LocalDate localDate : dateList) {
            if(userList != null && userList.size() > 0) {
                LocalDateTime beginT = LocalDateTime.of(localDate, LocalTime.MIN);
                LocalDateTime endT = LocalDateTime.of(localDate, LocalTime.MAX);
                for (User user : userList) {
                    if (beginT.isBefore(user.getCreateTime()) && endT.isAfter(user.getCreateTime())) {
                        newUser += 1;
                    }
                }
                totalUser += newUser;
            }
            newUserList.add(newUser);
            totalUserList.add(totalUser);
            newUser = 0;
        }

        userReportVO.setNewUserList(StringUtils.join(newUserList,","));
        userReportVO.setTotalUserList(StringUtils.join(totalUserList,","));

        return userReportVO;
    }

    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end,LocalTime.MAX);

        List<LocalDate> dateList = new ArrayList<>();
        List<Integer> totalOrderList = new ArrayList<>();
        List<Integer> validOrderList = new ArrayList<>();
        int validOrder = 0;
        int totalOrder = 0;
        int SumvalidOrder = 0;
        int SumtotalOrder = 0;

        dateList.add(begin);
        while (end.isAfter(begin)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        OrderReportVO orderReportVO = new OrderReportVO();
        orderReportVO.setDateList(StringUtils.join(dateList,","));

        List<Orders> orderList = orderMapper.GetOrderByDuring(beginTime,endTime,null);

        for (LocalDate localDate : dateList) {
            if(orderList != null && orderList.size() > 0) {
                LocalDateTime beginT = LocalDateTime.of(localDate, LocalTime.MIN);
                LocalDateTime endT = LocalDateTime.of(localDate, LocalTime.MAX);
                for (Orders order : orderList) {
                    if (beginT.isBefore(order.getOrderTime()) && endT.isAfter(order.getOrderTime())) {
                        totalOrder += 1;
                        if(order.getStatus().equals(Orders.COMPLETED)) validOrder += 1;
                    }
                }
                SumtotalOrder += totalOrder;
                SumvalidOrder += validOrder;
            }
            totalOrderList.add(totalOrder);
            validOrderList.add(validOrder);
            totalOrder = 0;
            validOrder = 0;
        }

        orderReportVO.setOrderCountList(StringUtils.join(totalOrderList,","));
        orderReportVO.setValidOrderCountList(StringUtils.join(validOrderList,","));
        orderReportVO.setTotalOrderCount(SumtotalOrder);
        orderReportVO.setValidOrderCount(SumvalidOrder);
        if(SumtotalOrder != 0)
        orderReportVO.setOrderCompletionRate(SumvalidOrder * 1.0 / SumtotalOrder);
        else orderReportVO.setOrderCompletionRate(0.0);

        return orderReportVO;
    }

    public SalesTop10ReportVO salesTop(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end,LocalTime.MAX);
        List<Map<String, Object>>dishMap = orderMapper.GetTop10ByDuring(beginTime,endTime);
        List<String> dishList = dishMap.stream().map(so -> so.get("name").toString()).toList();
        List<Integer> dishNumber = dishMap.stream().map(so -> Integer.parseInt(so.get("number").toString())).toList();
        SalesTop10ReportVO salesTop10ReportVO = SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(dishList,","))
                .numberList(StringUtils.join(dishNumber,","))
                .build();
        return salesTop10ReportVO;
    }

    public void dateExport(HttpServletResponse response) {
        //查数据库，获得数据
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(beginTime, endTime);
        //数据写入Excel文件
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);

            XSSFSheet sheet = excel.getSheet("Sheet1");
            //概览数据
            sheet.getRow(1).getCell(1).setCellValue("时间:"+ begin + "至" + end);
            sheet.getRow(3).getCell(2).setCellValue(businessDataVO.getTurnover());
            sheet.getRow(3).getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            sheet.getRow(3).getCell(6).setCellValue(businessDataVO.getNewUsers());
            sheet.getRow(4).getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            sheet.getRow(4).getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                BusinessDataVO businessDataVO1 = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                XSSFRow row = sheet.getRow(i+7);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessDataVO1.getTurnover());
                row.getCell(3).setCellValue(businessDataVO1.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO1.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVO1.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVO1.getNewUsers());

            }

            //文件下载到客户端
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            out.close();
            excel.close();


        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
